<template>
  <div ref="chartRef" style="height: 300px;"></div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  trendData: { type: Array, required: true },
  targetWeight: { type: Number, default: null }
});

const chartRef = ref(null);
let chartInstance = null;

const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

const renderChart = () => {
  if (!chartRef.value) return;
  if (chartInstance) chartInstance.dispose();
  chartInstance = echarts.init(chartRef.value);
  chartInstance.setOption({
    tooltip: {trigger: 'axis'},
    xAxis: {type: 'category', data: props.trendData.map(item => item.date)},
    yAxis: {
      type: 'value',
      scale: true,
      axisLabel: {formatter: '{value} kg'}
    },
    series: [{
      name: '体重',
      type: 'line',
      smooth: true,
      data: props.trendData.map(item => item.value),
      color: '#3ba272',

      // --- 【关键修复】 ---
      // 强制显示数据点，即使只有一个
      showSymbol: true,
      symbolSize: 10,
      // --- 修复结束 ---

      markLine: {
        silent: true,
        symbol: 'none',
        data: (props.targetWeight && props.targetWeight > 0)
            ? [
              {
                yAxis: props.targetWeight,
                name: '目标体重',
                lineStyle: {
                  color: '#FF6347',
                  type: 'dashed',
                },
                label: {
                  formatter: `目标: {c} kg`,
                  position: 'end',
                }
              }
            ]
            : []
      }
    }],
    grid: {left: '3%', right: '4%', bottom: '3%', containLabel: true}
  });
};

watch(() => [props.trendData, props.targetWeight], renderChart, {deep: true});

onMounted(() => {
  renderChart();
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  if (chartInstance) chartInstance.dispose();
});
</script>